package network;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {

    private DatagramSocket socket= null;
    private String serverIP;
    private int serverPort;
    // 客户端启动,需要知道服务器的IP和端口号
    public UdpEchoClient(String serverIP,int serverPort)
            throws SocketException {
        socket = new DatagramSocket();
        // 对于客户端不需要显式关联端口,服务器会自动分配
        this.serverIP = serverIP;
        this.serverPort = serverPort;
    }

    public void start() throws IOException {
        // 通过客户端和服务器多次进行交互
        Scanner scanner = new Scanner(System.in);
        while(true) {
           // 1.先从控制台,读取字符串
            // 打印提示符,提示用户输入内容
            System.out.print("->");
            String request = scanner.next();
           // 2.将字符串构造成Udp Packet,并进行发送
            DatagramPacket requestPacket = new DatagramPacket(
                    request.getBytes(),
                    request.getBytes().length,
                    InetAddress.getByName(serverIP),
                    serverPort
            );
            System.out.println(InetAddress.getByName(serverIP));
            socket.send(requestPacket);
           // 3.客户端尝试读取服务器返回的响应
            DatagramPacket responsePacket = new DatagramPacket(
                    new byte[4096],4096
            );
            socket.receive(responsePacket);
           // 4.把响应数据转换成string显示出来
            String response = new String(responsePacket.getData(),0,
                    responsePacket.getLength());
            System.out.printf("req %s resp %s\n ",request,response);
        }



    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1",9090);
        udpEchoClient.start();
    }


}
